package com.it.tydic.estate.module.controller.common;

import com.it.tydic.estate.common.aop.CodeMsg;
import com.it.tydic.estate.common.aop.Result;
import com.it.tydic.estate.common.security.TokenManager;
import com.it.tydic.estate.module.service.RedisCacheService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.aspectj.apache.bcel.classfile.Code;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.util.StringUtil;

import javax.servlet.http.HttpSession;
import java.util.UUID;

@RestController
@RequestMapping("token")
@Api(tags = "token管理接口")
public class TokenController {

    @Autowired
    private RedisCacheService redisCacheService;


    @GetMapping("/getToken")
    @ApiOperation(value = "获取token", notes = "token管理")
    public Result findById(HttpSession httpSession) { //@PathVariable 获取/get/{id}中id
        return Result.success(redisCacheService.get(httpSession.getId()));
    }

    @RequestMapping("/refreshToken/{refreshToken}")
    @ApiOperation(value = "根据id查询用", notes = "用户基本信息")
    @ApiImplicitParam(name = "refreshToken", value = "刷新token", paramType = "path", required = true, dataType = "String")
    public Result findById(HttpSession httpSession,@PathVariable String refreshToken) { //@PathVariable 获取/get/{id}中id
        if (StringUtil.isEmpty(refreshToken)) {
            Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        }
        Object object= redisCacheService.get(httpSession.getId());
        if(object != null){
            TokenManager tokenManager=(TokenManager)object;
            if(refreshToken.equals(tokenManager.getRefreshToken())){
                redisCacheService.delete(httpSession.getId());
                return Result.success( generateToken(httpSession));
            }
        }
        return Result.error(CodeMsg.INVALID_TOKEN);
    }
    /**
     * 获取token
     * @return
     */
    private TokenManager generateToken(HttpSession session) {
        String accessToken= UUID.randomUUID()+"";
        String refreshToken=UUID.randomUUID()+"";
        TokenManager tokenManager=new TokenManager();
        tokenManager.setAccessToken(accessToken);
        tokenManager.setRefreshToken(refreshToken);
        tokenManager.setExpiresIn(30L);
        tokenManager.setTokenType("bearer");
        boolean flag=redisCacheService.set(session.getId(),tokenManager,Long.valueOf(30));
        System.out.println(flag);
        System.out.println(redisCacheService.get(session.getId()));
        return tokenManager;
    }

}
